package com.company.example.concurrent.reentrantReadWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by ywl on 2017/2/16.
 */
public class CacheDemo {
    static Map<String,Object> map = new HashMap<String,Object>();
    static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    static Lock readLock = rwl.readLock();
    static Lock writeLock = rwl.writeLock();

    // 获取一个key对应的value
    public static final Object get(String key){
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" read to get value");
            return map.get(key);
        }finally {
            readLock.unlock();
        }
    }

    // 设置key对应的value，并返回旧的value
    public static final Object put(String key, Object value){
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" read to put key-value");
            return map.put(key,value);
        }finally {
            writeLock.unlock();
        }
    }

    // 清空所有的内容
    public static final void clear(){
        writeLock.lock();
        try {
            map.clear();
        }finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        final Integer[] keys = new Integer[]{0,1,2};
        for (Integer key : keys) {
            new Thread(){
                public void run(){
                    System.out.println("old value:"+CacheDemo.put(String.valueOf(key), new Random().nextInt(100)));
                }
            }.start();
        }

        for (Integer key : keys) {
            new Thread(){
                public void run(){
                    System.out.println(key+":"+CacheDemo.get(String.valueOf(key)));
                }
            }.start();
        }

        new Thread(){
            public void run(){
                System.out.println("old value:"+CacheDemo.put("0", new Random().nextInt(100)));
            }
        }.start();
    }
}
